package com.wujilee.mqdelaytask.service.mq;


import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author liwuji
 * @date 2024/5/31
 * @desc
 **/
@Configuration
public class MqSenderInitialization implements ApplicationContextAware {
    private static final AtomicBoolean init = new AtomicBoolean(false);
    private static final Map<String, MqSender> cache = new ConcurrentHashMap<>();
    private ApplicationContext applicationContext;

    public void init() {
        if (init.compareAndSet(false, true)) {
            Map<String, MqSender> beansOfType = applicationContext.getBeansOfType(MqSender.class);
            beansOfType.forEach((key, value) -> {
                cache.putIfAbsent(value.supportVersion(), value);
            });
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public MqSender getMqSender(String mq) {
        if (!init.get()) {
            throw new RuntimeException("初始化mq服务未完成");
        }
        MqSender mqSender = cache.get(mq);
        if (mqSender == null) {
            throw new RuntimeException("未找到对应的mq服务");
        }
        return mqSender;

    }

}
